<?php
namespace app\admin\controller;
use app\admin\model\AdminCate;
use think\Db;
use think\Session;
use app\admin\model\Admin as AdminModel;
use app\admin\model\Overtime as OvertimeModel;

/**
 * add by XiaHB
 * Class Overtime
 * @package app\admin\controller
 */
class Application extends Permissions {
    /**
     * 加班个人申请页
     * @return mixed
     */
    public function index(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        // 获取当前用户名称
        $adminModel = new AdminModel();
        $userInfo = $adminModel->where(["id" => $userId])->find();
        $nickName = $userInfo['nickname'];

        // 获取所有部门
        $sectionCate = Db::name('admin_cate')->where('is_prd', 0)->column('name','id');

        // 获取当前用户所在部门id
        $userCateId = Db::name('admin_cate_relation')->where('admin_id', $userId)->value('cate_id');

        $userRelation = $adminModel->where('is_prd', 0)->column('nickname','id');

        // 请假类型（1：调休，2：病假，3：事假，4：婚假，5：其他）
        $statusAll = [
            '1' => '调休',
            '2' => '病假',
            '3' => '事假',
            '4' => '婚假',
            '5' => '其他',
        ];

        $this->assign("nickName", $nickName);
        $this->assign("statusAll", $statusAll);
        $this->assign("userRelation", $userRelation);
        $this->assign("sectionCate", $sectionCate);
        $this->assign("cate_id", $userCateId);
        $this->assign("user_id", $userId);
        return $this->fetch("application/index");
    }

    /**
     * 请假申请提交
     */
    public function publish(){
        $adminModel = new AdminModel();
        $adminCateModel = new AdminCate();
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            echo 1;exit();// 未获取到用户信息，请重新登录
        }

        $userName = Db::name('admin')->where('id', $userId)->value('nickname');
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $beginTime = $post['begin_time'];// 加班申请开始时间
            $endTime = $post['end_time'];// 加班申请结束时间
            $account = $post['account'];// 加班说明
            $relationId = $post['relation_id'];// 加班说明
            $applicationStatus = $post['application_status'];// 加班说明
            $cateId = $post['cate_id'];// 部门id
            $bagId = $post['user_id'];// 申请人id（可以是自己提也可以是别人帮着提）
            if(empty($beginTime) || empty($endTime) || !isset($beginTime) || !isset($endTime)){
                echo 2;exit();
            }
            $approvalName = Db::name('admin')->where('id', $relationId)->value('nickname');

            $bagName = $adminModel->where('id', $bagId)->value('nickname');
            $cateName = $adminCateModel->where('id', $cateId)->value('name');// 部门名称

            // 计算间隔时长
            $beginTimeNew = strtotime($beginTime);
            $endTimeNew = strtotime($endTime);
            $sec = $endTimeNew - $beginTimeNew;
            $sec = round($sec/60);
            $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);
            $hours_min = floor($sec/60);
            if(30 == $min){
                $duration = $hours_min + '.5';
            }else{
                $duration = $hours_min;
            }

            if($beginTime >= $endTime) {
                echo 3;exit();// 请选择有效的时间范围区间
            }

            if($duration < 3) {
                echo 5;exit();
            }

            // 可用请假时长限制
            $overtimeAvailable = Db::name('overtime_personal')->where('user_id', $bagId)->value('overtime_available');
            if($duration > $overtimeAvailable){
                echo 6;exit();
            }


            $insertArray = [];
            $insertArray['apply_id'] = $bagId;// 申请人id
            $insertArray['cate_id'] = $cateId;
            $insertArray['bag_id'] = $userId;// 提交人id
            $insertArray['apply_name'] = $bagName;
            $insertArray['cate_name'] = $cateName;
            $insertArray['bag_name'] = $userName;
            $insertArray['approval_id'] = $relationId;
            $insertArray['approval_name'] = $approvalName;
            $insertArray['start_time'] = $beginTime;
            $insertArray['end_time'] = $endTime;
            $insertArray['duration'] = $duration;
            $insertArray['content'] = $account;
            $insertArray['application_type'] = $applicationStatus;
            $insertArray['status'] = 1;// 固定值
            $insertArray['type'] = 2;// 固定值
            $insertArray['is_show'] = 1;
            $insertArray['create_time'] = time();
            $insertArray['update_time'] = time();
            $insertId = Db::name('overtime')->insertGetId($insertArray);
            if(!$insertId){
                return $this->error('提交失败，请重试！');
            }else{
                return $this->success("请假时长： $duration 小时提交成功！",'admin/overtime/mylist');
            }
        } else {
            return $this->error("当前请求非法！");
        }
    }

    /**
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        $overtimeModel = new OvertimeModel();
        $post = $this->request->param();
        $where['apply_id'] = $userId;// 申请人id
        $where['type'] = 2;
        $where['is_show'] = 1;

        if (isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = strtotime($post['end_time']) + 24 * 60 * 60;
            $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
        }

        if (isset($post['overtime_type']) and !empty($post['overtime_type'])) {
            $where['type'] = $post['overtime_type'];
        }

        if (isset($post['audit_type']) and !empty($post['audit_type'])) {
            $where['status'] = $post['audit_type'];
        }

        $statusArray = [
            '1' => '待审批',
            '2' => '已审批',
            '3' => '驳回',
            '4' => '已使用',
            '5' => '已过期',
        ];

        $overtimeType = [
            '1' => '加班',
            '2' => '请假'
        ];

        $audit = [
            '1' => '待审批',
            '2' => '已通过',
            '3' => '驳回',
        ];

        $myList = empty($where) ? $overtimeModel->order('create_time desc')->paginate(10) : $overtimeModel->where($where)->order('create_time desc')->paginate(10, false, ['query' => $this->request->param()]);
        $durationData = Db::name('overtime_personal')->where('user_id', $userId)->find();
        $this->assign('myList', $myList);
        $this->assign('duration_all', (!empty($durationData['overtime_all']))?$durationData['overtime_all']:0);
        $this->assign('duration_un', (!empty($durationData['overtime_available']))?$durationData['overtime_available']:0);// 未使用
        $this->assign('durationAll_used', (!empty($durationData['overtime_used']))?$durationData['overtime_used']:0);// 已使用
        $this->assign('durationAll_out', (!empty($durationData['overtime_false']))?$durationData['overtime_false']:0);
        $this->assign('status_all', $statusArray);
        $this->assign('overtime_type', $overtimeType);
        $this->assign('audit', $audit);
        return $this->fetch("application/user_list");
    }



    public function auditList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }
        // 只有特定权限的人员能使用此功能
        $overtimeModel = new OvertimeModel();
//        $post = $this->request->param();
        $where['status'] = 0;
        $where['is_show'] = 1;

        $myList = empty($where) ? $overtimeModel->order('create_time desc')->paginate(10) : $overtimeModel->where($where)->order('create_time desc')->paginate(10, false, ['query' => $this->request->param()]);
        $this->assign('myList', $myList);
        return $this->fetch("overtime/auditList");

    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $info = Db::name('overtime')->where('id', $id)->update(['status'=>1]);
        if($info){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function fail(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $info = Db::name('overtime')->where('id', $id)->update(['status'=>2]);
        if($info){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $applicationInfo = Db::name('overtime')->where('id', $id)->find();
        if($applicationInfo && $applicationInfo['status'] == 2) {
            echo 3;exit();
        }
        $info = Db::name('overtime')->where('id', $id)->update(['is_show'=>0]);
        if($info){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }
}
